import React, {   useEffect, useRef, useState } from 'react'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Table, Button, Modal, Switch } from 'antd'
import axios from 'axios'
import UserForm from '../../../components/user-manage/UserForm';

const { confirm } = Modal;


export default function UserList() {
    // createRef()搞不定，会报错
    const addForm = useRef(null) 
    const updateForm = useRef(null) 
    // 注册用户信息
    const [dataSource, setdataSource] = useState([])
    // 管理员级别
    const [roleList, setroleList] = useState([])
    // 地区
    const [regionList, setregionList] = useState([])
    const [isAddVisible, setisAddVisible] = useState(false)
    const [isUpdateVisible, setisUpdateVisible] = useState(false)
    const [isUpdateDisabled, setisUpdateDisabled] = useState(false)

    const [current, setcurrent] = useState()

    const {roleId,region,username } = JSON.parse(localStorage.getItem('token'))
    
    useEffect(() => {
        const roleObj = {
            '1': 'superadmin',
            '2': 'admin',
            '3': 'editor'
        }
        axios.get('/users?_expand=role').then(res => {
            var list=res.data
            setdataSource(roleObj[roleId] === 'superadmin' ? list :[
                    // 接收自身数据
                    ...list.filter(item => item.username === username),
                    // 以及和自身同地区且低一级别的数据
                    ...list.filter(item => item.region === region && roleObj[item.roleId] === 'editor')
                ])
        })
    }, [roleId, region, username])
    useEffect(() => {
        axios.get('/regions').then(res => {
            setregionList(res.data)
        })
    }, [])

    useEffect(() => {
        axios.get('/roles').then(res => {
            setroleList(res.data)
        })
    }, [])
    // 删除功能
    const confirmMethod = (item) => {
        confirm({
            title: '你确定要删除吗?',
            icon: <ExclamationCircleOutlined />,
            // content: 'When clicked the OK button, this dialog will be closed after 1 second',
            onOk() {
                deleteMethod(item)
            },

            onCancel() {
                // console.log('取消');
            },
        });
    }

    // 删除方法
    const deleteMethod = (item) => {
        setdataSource(dataSource.filter(data => data.id !== item.id))

        axios.delete(`/users/${item.id}`)
    }

    // 用户状态开关
    const roleSwitchMethod = (item) => {
        item.roleState = !item.roleState
        setdataSource([...dataSource])

        axios.patch(`/users/${item.id}`,{
            roleState: item.roleState
        })

    }

    // 确定添加数据
    const addFormOK = () => {
        addForm.current.validateFields().then(value => {
            // console.log(value);
            setisAddVisible(false)
            // 清空上一条添加后，文本框中的数据
            addForm.current.resetFields()
            // 先post到后端，生产id，在设置dataSource
            axios.post('/users',{
                ...value,
                "roleState": true,
                "default": false,
            }).then(res=>{
                setdataSource([...dataSource,{
                    ...res.data,
                    // 添加数据后, 数据只是有roleId,但显示的是连表后role值，所有手动添加role
                    role: roleList.filter(item => item.id === value.roleId)[0]
                }])
            })

            

        }).catch(err => {
            console.log(err);
        })

    }
    // 确定更新数据
    const UpdateFormOK = () => {
        updateForm.current.validateFields().then(value => {
            // console.log(value);
            setisUpdateVisible(false)
            // 清空上一条添加后，文本框中的数据
            updateForm.current.resetFields()
           
            setdataSource(dataSource.map(item=>{
                if(item.id===current.id){
                    return {
                        ...item,
                        ...value,
                        role: roleList.filter(data => data.id === value.roleId)[0]

                    }
                }
                return item
            }))
            setisUpdateDisabled(!isUpdateDisabled)

            axios.patch(`/users/${current.id}`, value)

        }).catch(err => {
            console.log(err);
        })

    }

    // 修改数据
    const handleUpdate = (item)=>{
        // 热更新 还为set完，就执行下面的数据显示
        // setisUpdateVisible(true)
        // UpdateForm.current.setFieldsValue(item)
        // 开始创建表单出来(异步创建显示)
        setisUpdateVisible(true)
        setTimeout(()=>{
            if(item.roleId===1){
                setisUpdateDisabled(true)
            }else{
                setisUpdateDisabled(false)
            }
            updateForm.current.setFieldsValue(item)
        },0)
        setcurrent(item)
    }



    const columns = [
        {
            title: '区域',
            dataIndex: 'region',
            filters: [
                ...regionList.map(item=>({
                    text: item.label,
                    value:item.value,
                })),
                {
                    text: '全球',
                    value: '',
                }
            ],
            onFilter:(value,item)=>item.region===value,
            render: (region) => {
                return <b>{region === '' ? '全球' : region}</b>
            },
        },
        {
            title: '角色名称',
            dataIndex: 'role',
            render: (role) => {
                return role.roleName
            }

        },
        {
            title: '用户名',
            dataIndex: 'username',

        },
        {
            title: '用户状态',
            dataIndex: 'roleState',
            render: (roleState, item) => {
                return <Switch checked={roleState} disabled={item.default} onChange={() => roleSwitchMethod(item)}></Switch>
            }
        },
        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMethod(item)}
                        disabled={item.default} />
                    <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} 
                    onClick={()=>handleUpdate(item)}/>

                </div>
            },
        },
    ];
    return (
        <div>
            <Button type='primary' onClick={() => {
                setisAddVisible(true)
            }}>添加用户</Button>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 5,
            }}
                rowKey={(item) => item.id}
            />
            <Modal
                visible={isAddVisible}
                title="添加用户"
                okText="确定"
                cancelText="取消"
                onCancel={() => {
                    setisAddVisible(false)
                }}
                onOk={() => addFormOK()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={addForm}></UserForm>
            </Modal>

            <Modal
                visible={isUpdateVisible}
                title="更新用户"
                okText="更新"
                cancelText="取消"
                onCancel={() => {
                    setisUpdateVisible(false)
                    // 每次按取消进行取反,重更新,禁用全改为不禁,不禁全改为禁用
                    // 保证下一次点击修改,不同则改变，相同（与取反后）则不变
                    setisUpdateDisabled(!isUpdateDisabled)
                }}
                onOk={() => UpdateFormOK()}
            >
                <UserForm regionList={regionList} roleList={roleList} ref={updateForm}
                    isUpdateDisabled={isUpdateDisabled} 
                    isUpdate={true}></UserForm>
            </Modal>

        </div>
    )
}
